package demo22;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/* ReentrantLock用来替代synchronized
 * ReentrantLock必须要手动释放锁。使用synchronized锁定如果遇到异常，jvm会自动释放锁，但是Lock必须手动释放，因此常常在finally中释放锁*/
public class T {
    Lock lock = new ReentrantLock();

    void m1() {
        try {
            lock.lock();  //加锁  //相当于synchronized(this)
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(" " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();  //释放锁
        }
    }

    void m2() {
        lock.lock();  //加锁
        System.out.println(" m2()... ");
        lock.unlock();  //释放锁
    }

    public static void main(String[] args) {
        T t = new T();
        new Thread(t::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(t::m2).start();
    }

}